<template>
  <div class="content-frame" v-loading="loading">
    <search-modal :show.sync="searchMenu" :icon-show="false" :width="360">
      <Row class="mb-10">
        <i-col span="10">
          <search-modal-title :width="100">
            <Icon type="ios-search"/>
            高级查询
          </search-modal-title>
        </i-col>
        <i-col span="14" style="text-align: right;">
          <Button class="cust-btn" type="primary" @click="queryStock">查询</Button>
          <Button class="cust-btn" @click="reset">重置</Button>
        </i-col>
      </Row>
      <Form :label-width="80">
        <FormItem label="厂号：" style="margin-bottom: 5px">
          <Input v-model="searchForm.factoryCode" placeholder="按厂号查询" />
        </FormItem>
        <FormItem label="外部批次：" style="margin-bottom: 5px">
          <Input v-model="searchForm.batchNum" placeholder="按外部批次查询" />
        </FormItem>
        <FormItem label="质押状态：" style="margin-bottom: 5px">
          <Select v-model="searchForm.supervisionStatus" clearable>
            <Option value="1">已质押</Option>
            <Option value="0">未质押</Option>
          </Select>
        </FormItem>
        <FormItem label="入库日期：" style="margin-bottom: 5px">
          <DatePicker v-model="searchForm.dateInto" style="width: 100%" placeholder="请选择" type="daterange" transfer clearable
                      split-panels></DatePicker>
        </FormItem>
        <FormItem label="生产时间：" style="margin-bottom: 5px">
          <DatePicker v-model="searchForm.dateGen" style="width: 100%" placeholder="请选择" type="daterange" transfer clearable
                      split-panels></DatePicker>
        </FormItem>
        <FormItem label="失效时间：" style="margin-bottom: 5px">
          <DatePicker v-model="searchForm.dateExpire" style="width: 100%" placeholder="请选择" type="daterange" size="small" transfer
                      clearable split-panels></DatePicker>
        </FormItem>
      </Form>
    </search-modal>
    <div style="padding: 5px">
      <Tooltip placement="top" :content="`重量(KG)：${thousandthPercentile(currentWmsTotal.weightSum || 0)}`">
        <div class="warehouse-itemnew">
          <p class="flex" style="justify-content: space-between; align-items: center;">
            <span style="font-weight: 700;font-size: 16px;">{{ wareObj.whName }}</span>
          </p>
          <p class="flex" style="justify-content: space-between; align-items: center;">
            <span style="color: rgb(0, 0, 0);">重量(KG) | 托数(托)</span>
            <span
              style="font-weight: 700;font-size: 20px; margin-left: 10px">{{
                thousandthPercentile(currentWmsTotal.weightSum || 0)
              }} | {{ thousandthPercentile(currentWmsTotal.traceNumSum || 0) }}</span>
          </p>
          <p class="flex" style="justify-content: space-between; align-items: center;">
            <span style="color: rgb(0, 0, 0);">温度&nbsp;|&nbsp;湿度</span>
            <span style="font-weight: 700;font-size: 14px;">{{ temperature }}℃&nbsp;|&nbsp;{{ humidity }}%</span>
          </p>
        </div>
      </Tooltip>
    </div>
<!--    <div class="menu">-->
<!--      <div class="menu-items">-->
<!--        <p>{{ wareObj.whName }}</p>-->
<!--        <p>({{ customerSumObj.weightSum || 0 }}KG)</p>-->
<!--      </div>-->
<!--    </div>-->
    <div class="operate">
      <div>
        <Checkbox size="large" v-model="allCheck" @on-change="allCheckChange"><span style="font-weight: 700; font-size: 13px;">全选</span></Checkbox>
        <Input v-model="searchForm.matName" placeholder="按品名查询" style="width: 150px;"
                  @on-search="queryStock" search/>
        <Input v-model="searchForm.batchAttr07" placeholder="按柜号查询"
                  style="width: 150px; margin-left: 5px" @on-search="queryStock" search/>
        <Button class="cust-btn" type="primary" @click="searchMenu = true">高级查询</Button>
        <Button class="cust-btn" type="primary" @click="exportExcel" :loading="exportBtnLoading">导出</Button>
        <Button class="cust-btn" type="primary" @click="clickPledge('0')">质押</Button>
        <Button class="cust-btn" type="primary" @click="goodTransfer">货转申请</Button>

        <!--        <Button class="cust-btn" type="primary" @click="clickPledge('1')">解押</Button>-->
<!--        <Button class="cust-btn" type="primary" @click="releaseApprove">解押审核</Button>-->
<!--        <Button class="cust-btn" type="primary" @click="goodsAndOut">出库申请</Button>-->
      </div>
      <Page :total="listQuery.total" :current="listQuery.pageNum" :page-size="listQuery.pageSize"
            @on-change="pageChange" show-total></Page>
    </div>
    <div class="content-list">
      <div class="cus-card flex-item">
        <div>合计：</div>
        <div class="margin-left-10">柜数：<span class="font-weight">{{ thousandthPercentile(customerSumObj.boxNum || 0) }}</span> 柜</div>
        <div class="margin-left-10">总计数量：<span class="font-weight">{{ thousandthPercentile(customerSumObj.totalQtySum || 0) }}</span> 件
        </div>
        <div class="margin-left-10">可用件数：<span class="font-weight">{{ thousandthPercentile(customerSumObj.availableQtySum || 0) }}</span>
          件
        </div>
        <div class="margin-left-10">总重量：<span class="font-weight">{{ thousandthPercentile(customerSumObj.weightSum || 0) }}</span> KG</div>
        <div class="margin-left-10">托数：<span class="font-weight">{{ thousandthPercentile(customerSumObj.traceNumSum || 0) }}</span> 托</div>
      </div>
      <template v-if="list.length">
        <div class="card-scroll" style="height: calc(100vh - 340px)">
          <div class="cus-card" v-for="(item, index) in list" :key="index" @click="clickItem(item)">
            <div style="width: 20px; margin-right: 10px">
              <Checkbox size="large" v-model="item.checked" />
            </div>
            <div class="cus-content">
              <Row :gutter="5">
                <Col :span="3">
                  <span>柜号：</span>
                  {{ item.batchAttr07 }}
                </Col>
                <Col :span="3">
                  <span>品名：</span>
                  {{ item.matName }}
                </Col>
                <Col :span="3">
                  <span>外部批次：</span>
                  {{ item.batchNum }}
                </Col>
                <Col :span="3">
                  <span>厂号：</span>
                  {{ item.factoryCode }}
                </Col>
                <Col :span="3">
                  <span>总重量(KG)：</span>
                  {{ thousandthPercentile(item.sumMatWeight || 0) }}
                </Col>
                <Col :span="3">
                  <span>总计数量(件)：</span>
                  {{ thousandthPercentile(item.totalQty || 0)}}
                </Col>
                <Col :span="3">
                  <span>生产日期：</span>
                  {{ useDate(item.dateGen) }}
                </Col>
                <Col :span="3">
                  <span>失效日期：</span>
                  {{ useDate(item.dateExpire) }}
                </Col>
                <Col :span="3">
                  <span>可用数量(件)：</span>
                  {{ thousandthPercentile(item.availableQty || 0)}}
                </Col>
                <Col :span="3">
                  <span>使用托盘数(托)：</span>
                  {{ thousandthPercentile(item.traceNum || 0)}}
                </Col>
                <Col :span="3">
                  <span>冻结状态：</span>
                  {{ useDict(item.indBlkRmU, indBlkRmUList) }}
                </Col>
                <Col :span="3">
                  <span>质押状态：</span>
                  {{ useDict(item.supervisionStatus, supervisionStatusList) }}
                </Col>
                <Col :span="3">
                  <span>保税性质：</span>
                  {{ useDict(item.goodsBondedProperty, goodsBondedPropertyList) }}
                </Col>
                <Col :span="3">
                  <span>入库日期：</span>
                  {{ useDate(item.dateInto) }}
                </Col>
                <Col :span="3">
                  <span>质押日期：</span>
                  {{ useDate(item.superviseTime) }}
                </Col>
                <Col :span="3">
                  <span>解押日期：</span>
                  {{ useDate(item.removeSuperviseTime) }}
                </Col>
              </Row>
            </div>
          </div>
        </div>
      </template>
      <template v-else>
        <empty-comp/>
      </template>
    </div>
    <Modal
      :value="showCus"
      title="质押"
      :mask-closable="false"
      @on-ok="onCusOk"
      @on-cancel="onCusCancel"
      width="40%">
      <Form ref="formValidate" :model="cusFormItem" :label-width="80" label-position="right" :rules="ruleValidate">
        <FormItem label="当前货主">{{ customerName }}</FormItem>
        <FormItem label="质押货主" prop="newCargoOwner">
          <Select v-model="cusFormItem.newCargoOwner" filterable clearable :remote-method="remoteMethod">
            <Option v-for="(item, index) in ownerDataCopyList" :key="index" :value="item.ownerCode">{{item.ownerName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="金融标识">
          <Input v-model="cusFormItem.superviseCus" placeholder="请输入"/>
        </FormItem>
        <FormItem label="备注">
          <Input type="textarea" v-model="cusFormItem.remark" size="small"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="onCusOk" type="primary">确认</Button>
        <Button @click="onCusCancel" type="warning">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {getCurrentAgentPermissionWareHouse} from "@/libs/handleWareHouseList";
import {
  exportExcelHttp, thousandthPercentile,
  useCustomer,
  useCustomerName,
  useDate,
  useDict,
  useHttp,
  useHttpGet,
  useRandom, useRealName
} from "@/view/wms/js";
import fileDownload from "js-file-download";
import SearchModalTitle from "_c/search-modal/search-modal-title/index.vue";
import SearchModal from "_c/search-modal/index.vue";
import {supervisionStatusList, goodsTypeList, goodsBondedPropertyList, indBlkRmUList} from "./js/data";
import EmptyComp from "@/view/wms/comp/EmptyComp.vue";
import {getAllOwner} from "@/api/warehouse/home";


export default {
  name: "WmsStockInfo",
  components: {EmptyComp, SearchModal, SearchModalTitle},
  data() {
    return {
      ruleValidate: {
        newCargoOwner: [
          {required: true, message: '请选择', trigger: 'change'}
        ],
      },
      showCus: false,
      cusFormItem: {},
      allCheck: false,
      loading: false,
      exportBtnLoading: false,
      searchMenu: false,
      wareObj: {},
      searchForm: {},
      matTypeList: [],
      currentWmsTotal: {},
      wmsUrl: '',
      ownerDataList: [],
      humidity: 70,
      temperature: -19,
      customerSumObj: {},
      supervisionStatusList,
      goodsTypeList,
      goodsBondedPropertyList,
      indBlkRmUList,
      ownerDataCopyList: [],
      list: [],
      listQuery: {
        total: 0,
        pageNum: 1,
        pageSize: 50,
        filterList: [],
        sortList: [],
        searchKey: '',
        notInMatTypeCodeList: ["9999", "0001"]
      }
    }
  },
  computed: {
    customerName() {
      return useCustomerName(this);
    }
  },
  methods: {
    thousandthPercentile,
    useDict,
    useDate,
    clickItem(data) {
      data.checked = !data.checked;
      this.allCheck = this.list.length === this.getSelectData().length;
    },
    remoteMethod(query) {
      if (query) {
        setTimeout(() => {
          this.ownerDataCopyList = this.ownerDataList.filter(item => item.ownerName.indexOf(query) > -1);
        }, 100);
      } else {
        this.ownerDataCopyList = [];
      }
    },
    allCheckChange(val) {
      this.list.forEach(x => x.checked = val);
    },
    getSelectData() {
      return this.list.filter(item => item.checked);
    },
    clickPledge(flag) {
      const data = this.getSelectData();
      if (!data.length) {
        return this.$Message.warning('请选择数据！');
      }
      let judgeFlag = '0';
      let msg = '未质押';
      const isPledge = flag === '0';
      if (isPledge) {
        judgeFlag = '1';
        msg = '已质押'
      }
      if (data.filter(item => item.supervisionStatus === judgeFlag).length) {
        return this.$Message.warning(`所数据中已有${msg}的数据！`);
      }
      const ownerCode = data[0].ownerCode;
      if (data.some(i => i.ownerCode !== ownerCode)) {
        return this.$Message.warning('只能选择相同货主的库存进行操作！');
      }
      if (isPledge) {
        this.showCus = true;
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '是否将选中货物解押？',
          onOk: () => {
            useHttp('/api/wms_stock/removeSuperviseStock', data, this.wmsUrl).then(response => {
              if (response.data.returnCode === 200) {
                this.$Message.success(response.data.returnMsg);
                this.init();
              } else {
                this.$Message.error(response.data.returnMsg);
              }
            });
          },
          onCancel: () => {
            return false;
          }
        });
      }
    },
    onCusOk() {
      const data = this.getSelectData();
      const {newCargoOwner, superviseCus, remark} = this.cusFormItem;
      data.forEach(item => item.superviseCus = superviseCus);
      this.$Modal.confirm({
        title: '提示',
        content: '是否将选中货物质押锁库？',
        onOk: () => {
          useHttp('/api/ccis_pledge_apply/pledgeApply', {
            operationType: '0',
            cargoOwner: useCustomer(this),
            newCargoOwner,
            remark,
            confirm: 1,
            status: '1',
            operator: useRealName(this),
            stockList: data
          }, this.wmsUrl).then(response => {
            if (response.data.returnCode === 200) {
              this.$Message.success('操作成功');
              this.onCusCancel();
              this.init();
            } else {
              this.$Message.error(response.data.returnMsg);
            }
          });
        },
        onCancel: () => {
          return false;
        }
      });
    },
    onCusCancel() {
      this.$refs.formValidate.resetFields();
      this.showCus = false;
      this.cusFormItem = {};
      this.ownerDataCopyList = [];
    },
    goodTransfer() {
      const data = this.getSelectData();
      if (!data.length) {
        return this.$Message.warning('未选择货物, 请选择货物!');
      }
      if (data.every(x => !x.availableQty || x.availableQty == 0)) {
        return this.$Modal.warning({
          title: '提示',
          content: '您选择的库存已全部在申请作业中，不能重复申请，请检查或联系业务人员咨询，谢谢！',
          okText: '关闭'
        });
      }
      if (data.some(item => (item.indBlkRmU == 1 || item.supervisionStatus == 1))) {
        return this.$Message.warning('存在已冻结/已质押的货品');
      }
      this.$router.push({
        name: 'goodsTransfer',
        query: {
          tableData: JSON.stringify(data),
          menuActiveName: JSON.stringify(this.wareObj.id),
          wareList:JSON.stringify([this.wareObj]),
          wmsUrl:JSON.stringify(this.wmsUrl),
          ccisCustomerCode:JSON.stringify(useCustomer(this))
        }
      });
    },
    goodsAndOut() {
      const data = this.getSelectData();
      if (!data.length) {
        return this.$Message.warning('未选择货物, 请选择货物!');
      }
      if (data.every(x => !x.availableQty || x.availableQty == 0)) {
        this.$Modal.warning({
          title: '提示',
          content: '您选择的库存已全部在申请作业中，不能重复申请，请检查或联系业务人员咨询，谢谢！',
          okText: '关闭'
        });
        return;
      }
      if (data.some(item => (item.indBlkRmU == 1 || item.supervisionStatus == 1 || item.goodsBondedProperty == 2))) {
        return this.$Message.warning('存在已冻结/已质押/保税的货品');
      }
      this.$router.push({
        name: 'OutPlanInfo',
        query: {
          tableData: JSON.stringify(data),
          menuActiveName: JSON.stringify(this.wareObj.id),
          wareList:JSON.stringify([this.wareObj]),
          wmsUrl:JSON.stringify(this.wmsUrl),
          ccisCustomerCode:JSON.stringify(useCustomer(this))
        }
      });
    },
    releaseApprove() {
      const data = this.getSelectData();
      if (data.some(item => !(item.supervisionStatus !== '0' && item.goodsBondedProperty !== '2'))) {
        return this.$Message.warning('请选择已质押的库存!');
      }
      this.$Modal.confirm({
        title: '提示',
        content: '确定要解押审核吗？',
        onOk: () => {
          useHttp('/api/wms_stock/removeSuperviseReviewStock', data, this.wmsUrl).then(response => {
            if (response.data.returnCode === 200) {
              this.$Message.success(response.data.returnMsg);
              this.init();
            } else {
              this.$Message.error(response.data.returnMsg);
            }
          });
        },
        onCancel: () => {
          return false;
        }
      })
    },
    setTemHum() {
      const currentDay = new Date().getDate();
      const day = window.localStorage.getItem('day');
      if (!day || currentDay !== +day) {
        this.temperature = useRandom(-19, -23);
        this.humidity = useRandom(65, 70);
        window.localStorage.setItem('day', currentDay);
        window.localStorage.setItem('temHum', JSON.stringify({
          temperature: this.temperature,
          humidity: this.humidity
        }));
      } else {
        const {temperature, humidity} = JSON.parse(window.localStorage.getItem('temHum'));
        this.temperature = temperature;
        this.humidity = humidity;
      }
    },
    exportExcel() {
      if (!this.list.length) {
        return this.$Message.warning('暂无可导出数据');
      }
      this.exportBtnLoading = true;
      exportExcelHttp('/api/wms_stock/exportCcisSummaryExcel', this.listQuery, this.wmsUrl).then(response => {
        if (response.status === 200) {
          this.$success('操作成功');
          fileDownload(response.data, '库存查询信息.xlsx');
        }
      }).finally(() => {
        this.exportBtnLoading = false;
      })
    },
    init() {
      this.loading = true;
      this.allCheck = false;
      getCurrentAgentPermissionWareHouse().then(({data: returnData, message}) => {
        if (returnData) {
          if (!returnData.length) {
            return this.$Message.error('仓库信息为空！');
          }
          this.wareObj = returnData[0];
          this.wmsUrl = this.wareObj.ipProt;
          this.listQuery.ownerCodeList = [useCustomer(this)];
          this.getAllOwner();
          this.initData();
        } else if (message) {
          this.$Message.error(message);
        }
      })
    },
    getAllOwner() {
      getAllOwner(this.wmsUrl).then(res => {
        this.ownerDataList = res.data.returnData;
      });
    },
    reset() {
      this.searchForm = {};
      this.queryStock();
    },
    async initData() {
      await this.initDictData();
      this.getAllSumData();
      this.queryStock();
    },
    queryStock() {
      this.loading = true;
      this.listQuery.filterList = [{filterKey: 'whCode', filterValue: this.wareObj.whCode}];
      this.getFilterList();
      this.getSumData('signal');
      this.initStock();
    },
    getAllSumData() {
      this.getSumData('all');
    },
    getSumData(type) {
      let body = {...this.listQuery};
      useHttp('/api/wms_stock/selectStockDataList', body, this.wmsUrl).then(res => {
        const data = res.data.returnData;
        type === 'signal' ? (this.customerSumObj = data) : (this.currentWmsTotal = data);
      });
    },
    pageChange(pageNum) {
      this.listQuery.pageNum = pageNum;
      this.loading = true;
      this.queryStock();
    },
    initStock() {
      useHttp('/api/wms_stock/pageList', this.listQuery, this.wmsUrl).then(res => {
        const {list, total} = res.data.returnData.pageInfo;
        list.forEach(item => {
          item.show = false;
          item.checked = false
        });
        this.list = list;
        this.listQuery.total = total;
      }).finally(() => {
        this.loading = false;
      });
    },
    async initDictData() {
      try {
        const {data} = await useHttpGet('/api/dictionary/MAT_TYPE/list', {}, this.wmsUrl);
        this.matTypeList = data.returnData;
      } catch (e) {
        console.error(`获取字段数据失败-> ${e}`);
      }
    },
    getFilterList() {
      if (this.searchForm.matTypCode) {
        this.listQuery.filterList.push({
          filterKey: 'matTypCode',
          filterValue: this.searchForm.matTypCode
        });
      }
      if (this.searchForm.factoryCode) {
        this.listQuery.filterList.push({
          filterKey: 'factoryCode',
          filterValue: this.searchForm.factoryCode
        });
      }
      if (this.searchForm.supervisionStatus) {
        this.listQuery.filterList.push({
          filterKey: 'supervisionStatus',
          filterValue: this.searchForm.supervisionStatus
        });
      }
      if (this.searchForm.batchNum) {
        this.listQuery.filterList.push({
          filterKey: 'batchNum',
          filterValue: this.searchForm.batchNum
        });
      }
      if (this.searchForm.validatePeriod) {
        this.listQuery.filterList.push({
          filterKey: 'validatePeriod',
          filterValue: this.searchForm.validatePeriod
        });
      }
      if (this.searchForm.supervisionStatus) {
        this.listQuery.filterList.push({
          filterKey: 'supervisionStatus',
          filterValue: this.searchForm.supervisionStatus
        });
      }
      if (this.searchForm.productStatus) {
        this.listQuery.filterList.push({
          filterKey: 'productStatus',
          filterValue: this.searchForm.productStatus
        });
      }
      if (this.searchForm.batchAttr07) {
        this.listQuery.filterList.push({
          filterKey: 'batchAttr07',
          filterValue: this.searchForm.batchAttr07
        });
      }
      if (this.searchForm.matName) {
        this.listQuery.filterList.push({
          filterKey: 'matName',
          filterValue: this.searchForm.matName
        });
      }
      if (this.searchForm.qualityStatus) {
        this.listQuery.filterList.push({
          filterKey: 'qualityStatus',
          filterValue: this.searchForm.qualityStatus
        });
      }

      if (this.searchForm.dateInto && this.searchForm.dateInto.length > 0) {
        this.listQuery.filterList.push({
          filterKey: 'dateIntoStartDate',
          filterValue: this.$utils.dateToDateStr(this.searchForm.dateInto[0])
        });
        this.listQuery.filterList.push({
          filterKey: 'dateIntoEndDate',
          filterValue: this.$utils.dateToDateStr(this.searchForm.dateInto[1])
        });
      }
      if (this.searchForm.dateGen && this.searchForm.dateGen.length > 0) {
        this.listQuery.filterList.push({
          filterKey: 'dateGenStart',
          filterValue: this.$utils.dateToDateStr(this.searchForm.dateGen[0])
        });
        this.listQuery.filterList.push({
          filterKey: 'dateGenEnd',
          filterValue: this.$utils.dateToDateStr(this.searchForm.dateGen[1])
        });
      }
      if (this.searchForm.dateExpire && this.searchForm.dateExpire.length > 0) {
        this.listQuery.filterList.push({
          filterKey: 'dateExpireStart',
          filterValue: this.$utils.dateToDateStr(this.searchForm.dateExpire[0])
        });
        this.listQuery.filterList.push({
          filterKey: 'dateExpireEnd',
          filterValue: this.$utils.dateToDateStr(this.searchForm.dateExpire[1])
        });
      }
    },
  },
  mounted() {
    this.init();
    this.setTemHum();
  }
}
</script>

<style scoped lang="less">
@import "./style/index";
</style>
